package com.weikuang.fareast.activityNew;

import static net.lucode.hackware.magicindicator.buildins.UIUtil.getScreenWidth;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.licheedev.myutils.LogPlus;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.weikuang.fareast.R;
import com.weikuang.fareast.activity.BaseActivity;
import com.weikuang.fareast.adapter.AddListHkAdapter;
import com.weikuang.fareast.adapter.OutGoodsAdapter;
import com.weikuang.fareast.adapter.OutOrderAdapter;
import com.weikuang.fareast.bean.AddGoodsBean;
import com.weikuang.fareast.bean.AddListEvent;
import com.weikuang.fareast.bean.AddOrderInBean;
import com.weikuang.fareast.bean.BranchListByCustomer;
import com.weikuang.fareast.bean.CustomerBean;
import com.weikuang.fareast.bean.DriverListBean;
import com.weikuang.fareast.bean.HotelBean;
import com.weikuang.fareast.bean.OrderBean;
import com.weikuang.fareast.bean.OutGoodsBean;
import com.weikuang.fareast.bean.PrintOrderOutBean;
import com.weikuang.fareast.bean.ProductsByBranchBean;
import com.weikuang.fareast.bean.UsualGoodsBean;
import com.weikuang.fareast.network.KillerApi;
import com.weikuang.fareast.network.MainApi;
import com.weikuang.fareast.network.MyObserve;
import com.weikuang.fareast.utils.UserHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.dlc.commonlibrary.ui.widget.CommonItemView;
import cn.dlc.commonlibrary.ui.widget.TitleBar;
import cn.dlc.commonlibrary.ui.widget.popup.CommonPopupList;
import cn.dlc.commonlibrary.utils.ToastUtil;
import cn.dlc.commonlibrary.utils.rv_tool.RecyclerViewUtil;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

//出货单打印
public class OrderDetalisHkActivity extends BaseActivity  {

    @BindView(R.id.tv_mCustomer)
    TextView tv_mCustomer;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_mCustomer_Number)
    TextView tv_mCustomer_Number;
    @BindView(R.id.tv_order_Number)
    TextView tv_order_Number;

    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.tv_nums_1)
    TextView tv_nums_1;
    @BindView(R.id.tv_nums_2)
    TextView tv_nums_2;
    @BindView(R.id.tv_nums_3)
    TextView tv_nums_3;
    @BindView(R.id.tv_remark)
    TextView tv_remark;

    @BindView(R.id.tv_add_time)
    TextView tv_add_time;
    @BindView(R.id.tv_out_time)
    TextView tv_out_time;

    @BindView(R.id.btn_back)
    Button btn_back;

    PrintOrderOutBean printOrderOutBean;
    private OutOrderAdapter mOutOrderAdapter;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_details;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        printOrderOutBean = (PrintOrderOutBean)getIntent().getSerializableExtra("data");

        Observable.timer(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        captureWithoutStatusBar(getActivity());
                        ToastUtil.show(getActivity(),"送货单保存成功");

                    }
                });
        Observable.timer(3, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        openBitmap();
                    }
                });
        btn_back.setVisibility(View.GONE);
        Observable.timer(5, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        btn_back.setVisibility(View.VISIBLE);
                    }
                });

        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
       // captureWithoutStatusBar(getActivity());
       // getHotel();
        InitRecyclerView();

    }
    private void InitRecyclerView() {
        mOutOrderAdapter = new OutOrderAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mOutOrderAdapter);
        mOutOrderAdapter.setNewData(printOrderOutBean.getOrderOutDetails());
        int nums_1 = 0,nums_2= 0,nums_3 = 0;
        for (int i = 0;i < printOrderOutBean.getOrderOutDetails().size();i++){
            PrintOrderOutBean.OrderOutDetailsBean goodsBean = printOrderOutBean.getOrderOutDetails().get(i);
            nums_1 = nums_1+goodsBean.nums;
            nums_2 = nums_2+goodsBean.quantityCount;
        }
        nums_3 = Math.abs(nums_2-nums_1);
        tv_nums_1.setText(getString(R.string.order_50)+nums_1);
        tv_nums_2.setText(getString(R.string.order_51)+nums_2);
        tv_nums_3.setText(getString(R.string.order_52)+nums_3);

        tv_remark.setText("REMARKS :"+printOrderOutBean.remark);
        tv_mCustomer.setText(getString(R.string.order_54)+printOrderOutBean.customerName);
        tv_mCustomer_Number.setText(getString(R.string.order_55)+printOrderOutBean.code);
        tv_order_Number.setText("DN No.："+printOrderOutBean.order_No);

        tv_address.setText(getString(R.string.order_70)+printOrderOutBean.address);
        tv_phone.setText(getString(R.string.order_71)+printOrderOutBean.branchContactNumber);
        tv_add_time.setText(getString(R.string.order_68)+"：  "+printOrderOutBean.inboundDate);
        tv_out_time.setText(getString(R.string.order_69)+"：  "+printOrderOutBean.outboundDate);
        long currentTimeStamp = System.currentTimeMillis();
        Date date = new Date(currentTimeStamp);
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String currentTime = sdf.format(date);
        tv_time.setText("Date："+currentTime);

    }

    public  void captureWithoutStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int statusBarHeight = getStatusBarHeight(activity);
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap ret = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        saveData(ret);
    }

    /**
     * 得到屏幕的高
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 得到屏幕的宽
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 获取状态栏高度
     *
     * @param context 上下文
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources()
                .getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private void saveImageToAppDirectory(Uri imageUri) {
        try {
            // 获取输入流
            InputStream inputStream = getContentResolver().openInputStream(imageUri);
            // 创建文件名
            String fileName = System.currentTimeMillis() + ".jpg";
            // 获取应用私有目录
            File appDir = new File(getFilesDir(), "images");
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            // 创建文件
            File file = new File(appDir, fileName);
            // 获取输出流
            OutputStream outputStream = new FileOutputStream(file);
            // 复制数据
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            // 关闭流
            inputStream.close();
            outputStream.close();
            // 提示保存成功
            Toast.makeText(this, "图片保存成功", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "图片保存失败", Toast.LENGTH_SHORT).show();
        }
    }


    private void saveData(Bitmap bitmap){
        File folder = new File(Environment.getExternalStorageDirectory() + "/MyApp");
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdirs();
        }
        if (!success){
            return;
        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//        String formattedDate = sdf.format(new Date()); // 当前时间的字符串表示
//        File file = new File(folder.getPath() + "/order "+formattedDate+".txt");

        String fileName = "example.jpg";
        File file = new File(folder, fileName);
        try {
            OutputStream fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); // 将bitmap保存为JPEG格式，并设置质量为100%
            fOut.flush();
            fOut.close();
            Uri.fromFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *
     */

    private void openBitmap(){
        File folder = new File(Environment.getExternalStorageDirectory() + "/MyApp");
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdirs();
        }
        if (!success){
            return;
        }

        String fileName = "example.jpg";
        File file = new File(folder, fileName);
        openPhoto(file);
    }

    public void openPhoto(File file) {
        //File file = new File(filePath);
        //这里的file是获取你指定的一张图片的路径
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(getImageContentUri(file), "image/*");
        startActivity(intent);
    }

    /**
     * 转换 content:// uri
     *
     * @param imageFile
     * @return
     */
    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


}
